package com.cn.config;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.util.Set;

/**
 * @author xianglong.chen
 * @description
 * @time 2019-09-24 17:22
 */
@Configuration
public class LogbackDynamicLoggerAutoConfigure {

  private final static String ROOT_LOGGER_NAME = "ROOT";
  private final static String LOGGER_LEVEL_TAG = "logging.level.";
  private final Logger logger = LoggerFactory.getLogger(getClass());

  @ApolloConfig
  private Config config;

  @ApolloConfigChangeListener
  private void configChangeListter(ConfigChangeEvent changeEvent) {
    if (config == null) {
      logger.warn("the ucm2 config is null ,ignore change logger level!");
      return;
    }

    Set<String> keys = changeEvent.changedKeys();
    for (String key : keys) {
      if (key.contains(LOGGER_LEVEL_TAG)) {
        String strLevel = config.getProperty(key, "INFO");

        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        ch.qos.logback.classic.Logger logger = loggerContext.getLogger(ROOT_LOGGER_NAME);
        if (logger != null) {
          Level level = Level.toLevel(strLevel, null);
          if (level == null) {
            level = Level.INFO;
            logger.warn("the config of logback level({}) is error,so provided the info level!", strLevel);

          }
          logger.warn("change logger level {}:{}", key, level);
          logger.setLevel(level);
        }
      }
    }
  }

}
